package pe.edu.upc.dew.pharma.util;

import java.util.Properties;

import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import pe.edu.upc.dew.pharma.model.DetalleNotaPedido;
import pe.edu.upc.dew.pharma.model.NotaPedido;

public class ServerMail {

	private static final Log logger = LogFactory.getLog(ServerMail.class);
	
	public static final String HOST = "smtp.gmail.com";
	public static final int PORT = 587;
	public static final String USERNAME = "pharma.info.upc@gmail.com";
	public static final String PASSWORD = "pharma123456";
	public static final String CONTENT_TYPE = "text/html";

	private static boolean enviarMailHtml(String correoDestino, String asunto, String mensajeHtml){
		
		if(logger.isInfoEnabled()){
			logger.info("Enviando email html...");
			logger.info("correoDestino: " + correoDestino);
			logger.info("asunto: " + asunto);
			logger.info("mensajeHtml: " + mensajeHtml);
		}
		
		boolean success = false;
		
		Properties props = new Properties();
    	props.put("mail.smtp.auth", "true");
    	props.put("mail.smtp.starttls.enable", "true");
    	
    	Session session = Session.getInstance(props);
    	
    	Message message = new MimeMessage(session);
    	try {
			message.setFrom(new InternetAddress(USERNAME));
		} catch (AddressException e) {
			if(logger.isErrorEnabled()){
				logger.error("Pharma Error", e);
			}
			return false;
		} catch (MessagingException e) {
			if(logger.isErrorEnabled()){
				logger.error("Pharma Error", e);
			}
			return false;
		}
		
		try {
			message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(correoDestino));
		} catch (AddressException e) {
			if(logger.isErrorEnabled()){
				logger.error("Pharma Error", e);
			}
			return false;
		} catch (MessagingException e) {
			if(logger.isErrorEnabled()){
				logger.error("Pharma Error", e);
			}
			return false;
		}
		
		try {
			message.setSubject(asunto);
		} catch (MessagingException e) {
			if(logger.isErrorEnabled()){
				logger.error("Pharma Error", e);
			}
			return false;
		}
		
		Multipart multipart = new MimeMultipart();
		BodyPart htmlPart = new MimeBodyPart();
		try {
			htmlPart.setContent(mensajeHtml, CONTENT_TYPE);
		} catch (MessagingException e) {
			if(logger.isErrorEnabled()){
				logger.error("Pharma Error", e);
			}
			return false;
		}
		
		try {
			multipart.addBodyPart(htmlPart);
		} catch (MessagingException e) {
			if(logger.isErrorEnabled()){
				logger.error("Pharma Error", e);
			}
			return false;
		}
				
		try {
			message.setContent(multipart);
		} catch (MessagingException e) {
			if(logger.isErrorEnabled()){
				logger.error("Pharma Error", e);
			}
			return false;
		}
		
		Transport transport;
		try {
			transport = session.getTransport("smtp");
		} catch (NoSuchProviderException e) {
			if(logger.isErrorEnabled()){
				logger.error("Pharma Error", e);
			}
			return false;
		}
		
	    try {
			transport.connect(HOST, PORT, USERNAME, PASSWORD);
		} catch (MessagingException e) {
			if(logger.isErrorEnabled()){
				logger.error("Pharma Error", e);
			}
			return false;
		}
 
	    try {
			transport.sendMessage(message, message.getAllRecipients());
		} catch (MessagingException e) {
			if(logger.isErrorEnabled()){
				logger.error("Pharma Error", e);
			}
			return false;
		}
	    
	    try {
			transport.close();
		} catch (MessagingException e) {
			if(logger.isErrorEnabled()){
				logger.error("Pharma Error", e);
			}
			return false;
		}
	    
	    success = true;
	    
	    if(logger.isInfoEnabled()){
			logger.info("Email enviado a " + correoDestino);
		}
    	
		return success;
	}

	public static boolean enviarMailPedido(NotaPedido notaPedido) {
		String mensaje = notaPedido.getMensaje() + "\n";
		StringBuilder tabla = new StringBuilder();
		tabla.append("<table cellpadding='3' cellspacing='2' border='1'>");
		tabla
				.append("<tr><th>Codigo</th><th>Producto</th><th>Cantidad</th></tr>");
		for (DetalleNotaPedido detalle : notaPedido.getDetalles()) {
			tabla.append("<tr><td>" + detalle.getProducto().getIdProducto()
					+ "</td><td>" + detalle.getProducto().getNombre()
					+ "</td><td>" + detalle.getCantidad() + "</td></tr>");
		}
		tabla.append("</table>");
		tabla.append("\n\nPharma Peru");
		return enviarMailHtml(notaPedido.getProveedor().getCorreo(), "Pharma Logistica", mensaje + tabla.toString());
	}

}
